package icu.wdtt.Utils;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.dev33.satoken.temp.SaTempUtil;
import icu.wdtt.model.FileBase64;
import org.springframework.util.StringUtils;



/**
 * 验证码生成工具类
 * @author penghy
 * @date 2014-02-27
 */

public abstract class RandomCodeUtils {

    private static final String RANDOM_CODE_KEY = "check"; //验证码放在session中的key

    private static final int CODE_NUM = 4; //验证码字符个数

    // 设置图形验证码中字符串的字体和大小
    private static Font myFont = new Font("Arial", Font.BOLD, 16);

    //随机字符数组
    private static char[] charSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

    private static Random random = new Random();



    /**
     * 生成随机验证码
     * @param
     * @param response
     */
    public static FileBase64 createRandomCode(HttpServletResponse response){
        // 阻止生成的页面内容被缓存，保证每次重新生成随机验证码
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 指定图形验证码图片的大小
        int width = 80, height = 25;
        // 生成一张新图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 在图片中绘制内容
        Graphics g = image.getGraphics();
        g.setColor(getRandomColor(200, 250));
        g.fillRect(1, 1, width - 1, height - 1);
        g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setFont(myFont);
        // 随机生成线条，让图片看起来更加杂乱
        g.setColor(getRandomColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width - 1);// 起点的x坐标
            int y = random.nextInt(height - 1);// 起点的y坐标
            int x1 = random.nextInt(6) + 1;// x轴偏移量
            int y1 = random.nextInt(12) + 1;// y轴偏移量
            g.drawLine(x, y, x + x1, y + y1);
        }
        // 随机生成线条，让图片看起来更加杂乱
        for (int i = 0; i < 70; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int x1 = random.nextInt(12) + 1;
            int y1 = random.nextInt(6) + 1;
            g.drawLine(x, y, x - x1, y - y1);
        }

        // 该变量用来保存系统生成的随机字符串
        StringBuilder sRand = new StringBuilder(CODE_NUM);
        for (int i = 0; i < CODE_NUM; i++) {
            // 取得一个随机字符
            String tmp = getRandomChar();
            sRand.append(tmp);
            // 将系统生成的随机字符添加到图形验证码图片上
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(tmp, 15 * i + 10, 20);
        }
        //根据Sa-token验证码生成token,有效期为五分钟
        String checkId = SaTempUtil.createToken(sRand.toString(), 60 * 5);

        // 输出图形验证码图片
        try( //创建一个输出流
             ByteArrayOutputStream bos = new ByteArrayOutputStream()
        ) {
            //将图片写到输出流中
            ImageIO.write(image, "JPEG",bos);
            //获取图片的二进制编码
            byte[] bytes = bos.toByteArray();
            //转为base64编码
            String baseImage = Base64.getEncoder().encodeToString(bytes);
            return new FileBase64("验证码",
                    "data:image/jpeg;base64,"+baseImage,
                    String.valueOf(bytes.length),
                    "JPEG",
                    "checkId",
                    checkId);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查用户输入的验证码是否正确
     * @param checkId
     * @param inputCode
     * @return true: 正确, false:不正确
     */
    public static boolean checkRandomCode(String checkId, String inputCode){
        String code = null ;
        //根据token获取验证码的值
        if(checkId != null ){
            code = SaTempUtil.parseToken(checkId,String.class);
        }
        //HttpSession session = request.getSession(false);
        if(code != null && StringUtils.hasLength(inputCode)){
//            String code = (String) session.get(RANDOM_CODE_KEY);
            //logger.info("inputCode:"+inputCode.trim()+",code:"+code);
            return inputCode.trim().equalsIgnoreCase(code);
        }
        return false;
    }

    /**
     * 移除验证码
     * @param checkId
     *
     */
    public static void removeRandomCode(String checkId){
        //移除该token
        if(checkId != null){
            SaTempDelUtils.delToken(checkId);
        }
    }

    // 生成随机颜色
    private static Color getRandomColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    // 随机生成一个字符
    private static String getRandomChar() {
        int index = random.nextInt(charSequence.length);
        return String.valueOf(charSequence[index]);
    }
}
